package ru.sviridov.sellandbuy.json;

import java.lang.reflect.Type;

import ru.sviridov.sellandbuy.model.Response;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class ResponseDeserializer implements JsonDeserializer<Response>{
	
	public static final String RESULT = "Result";
	private static final String TYPE = "__type";
	
	@Override
	public Response deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		JsonObject obj = json.getAsJsonObject();
		JsonObject root = obj.getAsJsonObject("d"); //FIXME temporary. while server is fixing this bug
		Response response = context.deserialize(root, Response.class);
		
		JsonElement rootElement = root.get(RESULT);
		if(!rootElement.isJsonNull()){
			JsonArray jsonResults = rootElement.getAsJsonArray();
			Object[] results = new Object[jsonResults.size()];
			for(int i=0;i<results.length;i++){
				JsonObject resultObj = jsonResults.get(i).getAsJsonObject();
				Class<?> cls;
				try {
					cls = Class.forName(resultObj.get(TYPE).getAsString());
					results[i] = context.deserialize(resultObj, cls);
				} catch (ClassNotFoundException e) { e.printStackTrace();	}
			}
			response.setResults(results);			
		}
		
		return response;
	}

}
